<?php
class StudentsController extends AppController {

	var $name = 'Students';
	var $helpers = array('Html', 'Form');
	var $uses = array('Student');

	function index() {
	//	$this->Student->recursive = 0;
	//	$this->set('students', $this->paginate());


		// для установки факультета и курса
		$this->loadModel('Facultet');
/* 		$facultets = $this->Facultet->find('list');
		$this->set(compact('facultets')); */
		// читаем из сессии какие факультеты доступны
		$facultetsettings = $this->Session->read('FacultetsSettings');
		
		$tmpfacultets = $this->Facultet->find('all', array('conditions' => array('Facultet.id' => $facultetsettings), 'recursive' => -1));
		//debug($facultetsettings);
		foreach ($tmpfacultets as $facultet):
		$facultets[$facultet['Facultet']['id']] = $facultet['Facultet']['name'];
		endforeach;
		$this->set(compact('facultets'));
		
		$this->loadModel('Profession');
		$selectedprofessions = $this->Profession->find('list');
		$this->set(compact('selectedprofessions'));	
		$this->loadModel('Course');
		$selectedcourses = $this->Course->find('list');
		$this->set(compact('selectedcourses'));	
		$this->loadModel('Studentgroup');		
		$selectedgroups = $this->Studentgroup->find('list');
		$this->set(compact('selectedgroups'));					
		// вывод установки если есть
		// иницилизация переменных настроек
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = ''; 
		if ($this->Session->check('Settings')){
			$settings = $this->Session->read('Settings');
			$selectedfacultet = $settings['Settings']['selectedfacultet'];
			$selectedprofession = $settings['Settings']['selectedprofession'];
			$selectedcourse = $settings['Settings']['selectedcourse'];
			$selectedgroup = $settings['Settings']['selectedgroup'];			
		}
		$this->set(compact('selectedfacultet', $selectedfacultet)); 
		$this->set(compact('selectedprofession', $selectedprofession)); 
		$this->set(compact('selectedcourse', $selectedcourse));
		$this->set(compact('selectedgroup', $selectedgroup));
	}
	
	function settings_set() {
		if (!empty($this->data)) {
			$this->Session->delete('Settings');			
			$selectedfacultet = '';
			$selectedprofession = '';
			$selectedcourse = '';
			$selectedgroup = '';
			if ($this->data['Student']['facultet_id']) {
				$selectedfacultet = $this->data['Student']['facultet_id'];
			}
					if ($this->data['Student']['profession_id']) {
				$selectedprofession = $this->data['Student']['profession_id'];
			}
					if ($this->data['Student']['course_id']) {
				$selectedcourse = $this->data['Student']['course_id'];
			}
					if ($this->data['Student']['studentgroup_id']) {
				$selectedgroup = $this->data['Student']['studentgroup_id'];
			}			
			$settings = array('selectedfacultet' => $selectedfacultet,
								'selectedprofession' => $selectedprofession,
								'selectedcourse' => $selectedcourse,
								'selectedgroup' => $selectedgroup);
			$sessionsettings = array ('Settings' => $settings );
			$this->Session->write('Settings', $sessionsettings);
		}
	//	debug($this->data['Student']);
	 	$this->redirect(array('action' => 'index'));
	}

	function settings_unset() {
			if (!empty($this->data)) {
			$this->Session->delete('Settings');
		}
		$this->redirect(array('action' => 'index'));		
	}
		function update_profession () {
		
	  if(!empty($this->data['Student']['facultet_id'])) {
	    $facultet_id = $this->data['Student']['facultet_id'];
	    $this->loadModel('Profession');
	    $options = $this->Profession->find('list', array('conditions' => array ('Profession.facultet_id' => $facultet_id)));
	    $this->set(compact('options'));
	  }	
	}
	
	function update_course () {
	  if(!empty($this->data['Student']['profession_id'])) {
	    $profession_id = $this->data['Student']['profession_id'];
	    $this->loadModel('Course');
	    $options = $this->Course->find('list', array('conditions' => array ('Course.profession_id' => $profession_id)));
	    $this->set(compact('options'));
	  }	
	}

	function update_studentgroup () {
	  if(!empty($this->data['Student']['course_id'])) {
	    $course_id = $this->data['Student']['course_id'];
	    $this->loadModel('Studentgroup');
	    $options = $this->Studentgroup->find('list', array('conditions' => array ('Studentgroup.course_id' =>  $course_id)));
	    $this->set(compact('options'));
	  }	
	}

	function liststudents() {
		// определяем формат результата
		$format = $this->data['Student']['format'];
		
		$sessionsettings = ''; 
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = ''; 
		if ($this->Session->check('Settings')){
			$sessionsettings = $this->Session->read('Settings');
			$selectedfacultet = $sessionsettings['Settings']['selectedfacultet'];
			$selectedprofession = $sessionsettings['Settings']['selectedprofession'];
			$selectedcourse = $sessionsettings['Settings']['selectedcourse'];
			$selectedgroup = $sessionsettings['Settings']['selectedgroup'];			
		} else {
			// если настрое отображения нет берем настройки вывода факультетов из facultetssettings
			$facultetsettings = $this->Session->read('FacultetsSettings');
			//$selectedfacultet
		}
		$this->set(compact('selectedfacultet', $selectedfacultet)); 
		$this->set(compact('selectedprofession', $selectedprofession)); 
		$this->set(compact('selectedcourse', $selectedcourse));
		$this->set(compact('selectedgroup', $selectedgroup));
		/********************************************************************************************/		
		// выбран факультет спецальность курс группа
		/********************************************************************************************/		
		if ($selectedfacultet && $selectedprofession && $selectedcourse && $selectedgroup) {
			// $students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroup), 'recursive' => 0));
			//формируем массив id групп
			$selectedgroups_ids = array();
			array_push($selectedgroups_ids, $selectedgroup);
		}
		/********************************************************************************************/		
		// выбран факультет специлальность курс
		/********************************************************************************************/		
		else if ($selectedfacultet && $selectedprofession && $selectedcourse && !$selectedgroup) {
			// выбираем группы курса
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourse), 
			'recursive' => 0,
			'order' => 'Studentgroup.id ASC',
			'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
		//	$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
		}
		/********************************************************************************************/		
		// выбран факультет специальность
		/********************************************************************************************/		
		else if ($selectedfacultet && $selectedprofession && !$selectedcourse && !$selectedgroup) {
			// выбираем курсы специальности
			$this->loadModel('Course');
			$selectedcourses = $this->Course->find('all', array('conditions' => array('Course.profession_id' => $selectedprofession),
			'recursive' => 0,
			'order' => 'Course.id ASC',
			'fields' => array('Course.id')));
			$selectedcourses_ids = array();
			foreach ($selectedcourses as $element):
			array_push($selectedcourses_ids, $element['Course']['id']);
			endforeach;
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourses_ids), 
			'recursive' => 0,
			'order' => 'Studentgroup.id ASC',
			'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
		//	$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
		}
		/********************************************************************************************/		
		// выбран факультет
		/********************************************************************************************/		
		if ($selectedfacultet && !$selectedprofession && !$selectedcourse && !$selectedgroup) {
			// выбираем специальности факультета
			$this->loadModel('Profession');
			$selectedprofessions = $this->Profession->find('all', array('conditions' => array('Profession.facultet_id' => $selectedfacultet), 'recursive' => 0));
			$selectedprofessions_ids = array();
			foreach ($selectedprofessions as $element):
			array_push($selectedprofessions_ids, $element['Profession']['id']);
			endforeach;			
			// выбираем курсы специальностей
			$this->loadModel('Course');
			$selectedcourses = $this->Course->find('all', array('conditions' => array('Course.profession_id' => $selectedprofessions_ids),
			'recursive' => 0,
	//		'order' => 'Course.id ASC',
			'fields' => array('Course.id')));
			$selectedcourses_ids = array();
			foreach ($selectedcourses as $element):
			array_push($selectedcourses_ids, $element['Course']['id']);
			endforeach;
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourses_ids), 
			'recursive' => 0,
	//		'order' => 'Studentgroup.id ASC',
			'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
			// $students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
			}
		/********************************************************************************************/
		// выбрано все факультеты
		/********************************************************************************************/		
		else if (!$selectedfacultet && !$selectedprofession && !$selectedcourse && !$selectedgroup) {
			//$this->Student->recursive = 0;
			//$students = $this->Student->find('all');
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all');
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;			
		}
		// выбираем инфо для заполнения столбцов в таблице
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this->loadModel('Learningtype');
		$this->set('learningforms', $learningforms);
		$learningtypes = $this->Learningtype->find('list');
		$this->set('learningtypes', $learningtypes);
		// id массива professions начинается с 0 так что  чобы получить profession с id = 8 нужно взять 7 элемент массива
		$this->LoadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		$this->LoadModel('Course');
		$courses = $this->Course->find('all', array('recursive' => 0));
		// id массива courses начинается с 0 так что чтобы получить course с id = 12 нужно взять 11 элемент массива
		$this->set('courses', $courses);
		
		$this->set('format', $format);
		if ($format == 0){
			// устнавливем пагинацию
			$this->Student->recursive = 0;
			$conditions =  array('Student.studentgroup_id' => $selectedgroups_ids);
			$this->paginate['conditions'] = $conditions;
			$students = $this->paginate('Student');
			$this->set('students', $students);
		} else { // если не устанавливать пагинацию то нужно выбрать студентов самому
			
			$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids)));
			$this->set('students', $students);
			if ($format == 1){
				$this->render('/', 'default', 'liststudentsnopagination');
			}
			// если выводим в файл значит подключить blank шаблон
			if (($format == 2) || ($format == 3)){
				$this->render('/', 'blank', 'liststudentsnopagination');
			}			
		}




	}
	
	/*
	 * вывод студентов факультета проживающих в общежитии
	 */
	function listhostelstudents () {
		// определяем формат результата
		$format = $this->data['Student']['format'];
		
		$sessionsettings = '';
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = '';
		if ($this->Session->check('Settings')){
			$sessionsettings = $this->Session->read('Settings');
			$selectedfacultet = $sessionsettings['Settings']['selectedfacultet'];
/* 			$selectedprofession = $sessionsettings['Settings']['selectedprofession'];
			$selectedcourse = $sessionsettings['Settings']['selectedcourse'];
			$selectedgroup = $sessionsettings['Settings']['selectedgroup']; */
		} /* else {
			// если настрое отображения нет берем настройки вывода факультетов из facultetssettings
			$facultetsettings = $this->Session->read('FacultetsSettings');
			//$selectedfacultet
		} */
		// выбран только факультет
		
		// выбираем специальности факультета
		$this->loadModel('Profession');
		$selectedprofessions = $this->Profession->find('all', array('conditions' => array('Profession.facultet_id' => $selectedfacultet), 'recursive' => 0));
		$selectedprofessions_ids = array();
		foreach ($selectedprofessions as $element):
		array_push($selectedprofessions_ids, $element['Profession']['id']);
		endforeach;
		// выбираем курсы специальностей
		$this->loadModel('Course');
		$selectedcourses = $this->Course->find('all', array('conditions' => array('Course.profession_id' => $selectedprofessions_ids),
					'recursive' => 0,
		//		'order' => 'Course.id ASC',
					'fields' => array('Course.id')));
		$selectedcourses_ids = array();
		foreach ($selectedcourses as $element):
		array_push($selectedcourses_ids, $element['Course']['id']);
		endforeach;
		// выбираем группы курсов
		$this->loadModel('Studentgroup');
		$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourses_ids),
					'recursive' => 0,
		//		'order' => 'Studentgroup.id ASC',
					'fields' => array('Studentgroup.id')));
		//формируем массив id групп
		$selectedgroups_ids = array();
		foreach ($selectedgroups as $element):
		array_push($selectedgroups_ids, $element['Studentgroup']['id']);
		endforeach;
		
		$this->LoadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		$this->LoadModel('Course');
		$courses = $this->Course->find('all', array('recursive' => 0));
		// id массива courses начинается с 0 так что чтобы получить course с id = 12 нужно взять 11 элемент массива
		$this->set('courses', $courses);
		
		// выбираем id всех студентов факультетов
		$hostelstudents = array();
		$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids)));
		// подгружаем модель HostelsStudent
		$this->loadModel('HostelsStudent');
		foreach ($students as $student):
			$hostelstudent = $this->HostelsStudent->find('all', array('conditions' => array('HostelsStudent.student_id' => $student['Student']['id']))); 
			if ($hostelstudent){
				array_push($hostelstudent[0], $student);
				array_push($hostelstudents, $hostelstudent[0]);
			}
		endforeach;
		
		// debug ($hostelstudents);
		$this->set('students', $hostelstudents);
		$this->set('format', $format);
		if ($format == 1){
			$this->render('/', 'default', 'listhostelstudents');
		}
		// если выводим в файл значит подключить blank шаблон
		if (($format == 2) || ($format == 3)){
			$this->render('/', 'blank', 'listhostelstudents');
		}
		//$this->set('students', $students); 
	}
	
	
	
	
	
/* 	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Student', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('student', $this->Student->read(null, $id));
	}
 */
/* 	function add() {
		if (!empty($this->data)) {
			$this->Student->create();
			if ($this->Student->save($this->data)) {
				$this->Session->setFlash(__('Студент был добавлен!', true));
				$this->redirect(array('controller' =>'studentinfos', 'action' => 'add/student_id:'.$this->Student->id));
			} else {
				$this->Session->setFlash(__('The Student could not be saved. Please, try again.', true));
			}
		}
	//	$orders = $this->Student->Order->find('list');
	// 	$studentgroups = $this->Student->Studentgroup->find('list');
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = ''; 
		if ($this->Session->check('Settings')){
			$settings = $this->Session->read('Settings');
			$selectedfacultet = $settings['Settings']['selectedfacultet'];
			$selectedprofession = $settings['Settings']['selectedprofession'];
			$selectedcourse = $settings['Settings']['selectedcourse'];
			$selectedgroup = $settings['Settings']['selectedgroup'];			
		}
		$this->set(compact('selectedfacultet', $selectedfacultet)); 
		$this->set(compact('selectedprofession', $selectedprofession)); 
		$this->set(compact('selectedcourse', $selectedcourse));
		$this->set(compact('selectedgroup', $selectedgroup));
		// для вывода 
		// для установки факультета и курса
		$this->loadModel('Facultet');
		$selectedfacultets = $this->Facultet->find('list');
		$this->set(compact('selectedfacultets'));
		$this->loadModel('Profession');
		$selectedprofessions = $this->Profession->find('list');
		$this->set(compact('selectedprofessions'));	
		$this->loadModel('Course');
		$selectedcourses = $this->Course->find('list');
		$this->set(compact('selectedcourses'));	
		$this->loadModel('Studentgroup');		
		$selectedgroups = $this->Studentgroup->find('list');
		$this->set(compact('selectedgroups'));		
		// для вывода вариативной части		
		$studentstates = $this->Student->Studentstate->find('list');
		$learningforms = $this->Student->Learningform->find('list');
		$learningtypes = $this->Student->Learningtype->find('list');
		$this->set(compact('orders', 'studentgroups', 'studentstates', 'learningforms', 'learningtypes'));
	} */

/* 	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Student', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->data['Student']['studentgroup_id'] == ''){
				$this->data['Student']['studentgroup_id'] = $this->data['Student']['oldstudentgroup_id'];
			}
			if ($this->Student->save($this->data)) {
				$this->Session->setFlash(__('Данные сохранены!', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The Student could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Student->read(null, $id);
		}
		// для установки факультета и курса
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set(compact('facultets'));		
		$studentstates = $this->Student->Studentstate->find('list');
		$learningforms = $this->Student->Learningform->find('list');
		$learningtypes = $this->Student->Learningtype->find('list');
		$this->set(compact('studentstates', 'learningforms', 'learningtypes'));		
		
		$this->loadModel('Profession');
		$professions = $this->Profession->find('list'); 
		$this->loadModel('Course');
		$courses = $this->Course->find('list');	
		$this->LoadModel('Studentgroup');
		$current_studentgroup = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.id' => $this->data['Student']['studentgroup_id']), 'recursive' => 0,));
		$this->set('current_studentgroup', $current_studentgroup);	
		//debug($current_studentgroup);	
		$current_profession = $this->Profession->find('all', array('conditions' => array('Profession.id' => $current_studentgroup[0]['Course']['profession_id']), 'recursive' => 0));
		$this->set('current_profession', $current_profession);	
		//debug($current_profession);	
		$this->set(compact('professions', 'courses'));
		// $orders = $this->Student->Order->find('list');
		// $studentgroups = $this->Student->Studentgroup->find('list');
		// $studentstates = $this->Student->Studentstate->find('list');
		// $this->set(compact('orders','studentgroups','studentstates'));
	} */

/* 	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Student', true));
			$this->redirect(array('action' => 'index'));
		}
		if ($this->Student->del($id)) {
			$this->Session->setFlash(__('Student deleted', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('The Student could not be deleted. Please, try again.', true));
		$this->redirect(array('action' => 'index'));
	} */

}
?>